<template>
  <div class="map-location-picker">

    <!-- 搜索框 -->
    <div class="search-section">
      <a-input-search
        v-model:value="searchKeyword"
        placeholder="搜索地点，如：北京天安门"
        enter-button="搜索"
        size="large"
        @search="handleSearch"
        :loading="searchLoading"
        class="search-input"
      >
        <template #prefix>
          <SearchOutlined />
        </template>
      </a-input-search>
    </div>

    <!-- 搜索结果列表 -->
    <div v-if="searchResults.length > 0" class="search-results">
      <div class="results-header">
        <span class="results-title">搜索结果</span>
        <a-button type="text" size="small" @click="clearSearchResults">
          <template #icon>
            <CloseOutlined />
          </template>
          清除
        </a-button>
      </div>
      <div class="results-list">
        <div
          v-for="(result, index) in searchResults"
          :key="index"
          class="result-item"
          @click="selectSearchResult(result)"
        >
          <div class="result-info">
            <div class="result-name">{{ result.name }}</div>
            <div class="result-address">{{ result.address }}</div>
          </div>
          <div class="result-location">
            <span class="location-text">{{ result.latitude }}, {{ result.longitude }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 地图显示区域 -->
    <div class="map-display">
      <div class="map-header">
        <span class="map-title">地图选点</span>
        <div class="map-actions">
          <a-button v-if="selectedLocation" type="primary" size="small" @click="confirmSelection">
            确认选择
          </a-button>
          <a-button type="text" size="small" @click="getCurrentLocation">
            <template #icon>
              <AimOutlined />
            </template>
            定位
          </a-button>
        </div>
      </div>
      
      <!-- 地图容器 -->
      <div class="map-container" ref="mapContainer">
        <div v-if="!mapUrl" class="map-placeholder">
          <EnvironmentOutlined style="font-size: 48px; color: #ccc;" />
          <p>点击搜索或定位来显示地图</p>
        </div>
        <div v-else class="map-content">
          <img 
            :src="mapUrl" 
            alt="地图" 
            class="map-image"
            @click="handleMapClick"
            @load="onMapLoad"
            @error="onMapError"
          />
          <!-- 地图标记点 -->
          <div 
            v-if="selectedLocation" 
            class="map-marker"
            :style="getMarkerStyle()"
          >
            <EnvironmentFilled class="marker-icon" />
          </div>
        </div>
      </div>
    </div>

    <!-- 选中位置信息 -->
    <div v-if="selectedLocation" class="selected-location">
      <div class="location-header">
        <span class="location-title">选中位置</span>
        <a-button type="text" size="small" @click="clearSelection">
          <template #icon>
            <CloseOutlined />
          </template>
          清除
        </a-button>
      </div>
      <div class="location-details">
        <div class="location-item">
          <span class="label">位置名称：</span>
          <span class="value">{{ selectedLocation.name || '未知位置' }}</span>
        </div>
        <div class="location-item">
          <span class="label">详细地址：</span>
          <span class="value">{{ selectedLocation.address || '获取中...' }}</span>
        </div>
        <div class="location-item">
          <span class="label">经纬度：</span>
          <span class="value">{{ selectedLocation.latitude }}, {{ selectedLocation.longitude }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { 
  SearchOutlined, 
  CloseOutlined, 
  EnvironmentOutlined, 
  EnvironmentFilled,
  AimOutlined
} from '@ant-design/icons-vue'
import { anyGet, anyPost } from '@/network'

interface LocationData {
  latitude: number
  longitude: number
  name?: string
  address?: string
}

interface SearchResult {
  name: string
  address: string
  latitude: number
  longitude: number
}

const props = defineProps<{
  modelValue?: LocationData
  placeholder?: string
  disabled?: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: LocationData | undefined]
  'change': [value: LocationData | undefined]
}>()

// 高德地图配置 - 请在此处填写您的API密钥
const mapConfig = {
  // 请填写您的高德地图Web服务API Key
  webApiKey: '071b8f5338cb68f9447b7474c0813c7e',
  // 请填写您的安全密钥（2021年12月后申请的key必须配置）
  securityJsCode: '188f4e1210fe7e98f019eea65731627a'
}

// 搜索相关
const searchKeyword = ref('')
const searchLoading = ref(false)
const searchResults = ref<SearchResult[]>([])

// 地图相关
const mapUrl = ref('')
const mapContainer = ref<HTMLElement>()
const selectedLocation = ref<LocationData | undefined>(props.modelValue)
const mapZoom = ref(15)
const mapSize = { width: 600, height: 400 }

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
  selectedLocation.value = newValue
  if (newValue) {
    loadMapWithLocation(newValue)
  }
}, { immediate: true })

// 地理编码（使用前端直接调用高德API）
const geocodeWithAmap = async (address: string): Promise<any> => {
  if (!mapConfig.webApiKey || mapConfig.webApiKey === 'YOUR_AMAP_WEB_API_KEY_HERE') {
    throw new Error('请先在代码中配置Web API Key')
  }
  
  // 构建URL参数
  let url = `https://restapi.amap.com/v3/geocode/geo?key=${mapConfig.webApiKey}&address=${encodeURIComponent(address)}`
  
  // 添加安全密钥支持
  if (mapConfig.securityJsCode && mapConfig.securityJsCode !== 'YOUR_AMAP_SECURITY_JSCODE_HERE') {
    url += `&jscode=${mapConfig.securityJsCode}`
  }
  
  try {
    const response = await fetch(url)
    const data = await response.json()
    
    if (data.status === '1' && data.geocodes && data.geocodes.length > 0) {
      const geocode = data.geocodes[0]
      const [lng, lat] = geocode.location.split(',')
      return {
        latitude: parseFloat(lat),
        longitude: parseFloat(lng),
        address: geocode.formatted_address,
        name: address
      }
    } else {
      throw new Error(data.info || '地理编码失败')
    }
  } catch (error) {
    throw new Error('地理编码请求失败: ' + error.message)
  }
}

// 逆地理编码（使用前端直接调用高德API）
const reverseGeocodeWithAmap = async (lng: number, lat: number): Promise<any> => {
  if (!mapConfig.webApiKey || mapConfig.webApiKey === 'YOUR_AMAP_WEB_API_KEY_HERE') {
    throw new Error('请先在代码中配置Web API Key')
  }
  
  // 构建URL参数
  let url = `https://restapi.amap.com/v3/geocode/regeo?key=${mapConfig.webApiKey}&location=${lng},${lat}`
  
  // 添加安全密钥支持
  if (mapConfig.securityJsCode && mapConfig.securityJsCode !== 'YOUR_AMAP_SECURITY_JSCODE_HERE') {
    url += `&jscode=${mapConfig.securityJsCode}`
  }
  
  try {
    const response = await fetch(url)
    const data = await response.json()
    
    if (data.status === '1' && data.regeocode) {
      const regeocode = data.regeocode
      return {
        address: regeocode.formatted_address,
        name: regeocode.addressComponent?.building || regeocode.addressComponent?.poi || '未知位置'
      }
    } else {
      throw new Error(data.info || '逆地理编码失败')
    }
  } catch (error) {
    throw new Error('逆地理编码请求失败: ' + error.message)
  }
}

// 搜索地点
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    message.warning('请输入搜索关键词')
    return
  }
  
  if (!mapConfig.webApiKey || mapConfig.webApiKey === 'YOUR_AMAP_WEB_API_KEY_HERE') {
    message.error('请先在代码中配置Web API Key')
    return
  }

  searchLoading.value = true
  try {
    // 优先使用前端直接调用高德API
    const result = await geocodeWithAmap(searchKeyword.value)
    
    // 构造搜索结果
    const searchResult: SearchResult = {
      name: result.name,
      address: result.address,
      latitude: result.latitude,
      longitude: result.longitude
    }
    searchResults.value = [searchResult]
    
    // 自动选择第一个结果
    selectSearchResult(searchResult)
  } catch (error) {
    console.error('前端搜索失败，尝试后端接口:', error)
    
    // 如果前端调用失败，回退到后端接口
    try {
      const response = await anyPost('/api/map/geocode', searchKeyword.value)
      if (response && response.data) {
        const result = response.data
        const searchResult: SearchResult = {
          name: searchKeyword.value,
          address: result.address || '',
          latitude: result.latitude,
          longitude: result.longitude
        }
        searchResults.value = [searchResult]
        selectSearchResult(searchResult)
      } else {
        message.error('未找到相关地点')
      }
    } catch (backendError) {
      console.error('后端搜索也失败:', backendError)
      message.error('搜索失败，请检查网络连接或API配置')
    }
  } finally {
    searchLoading.value = false
  }
}

// 选择搜索结果
const selectSearchResult = (result: SearchResult) => {
  const location: LocationData = {
    latitude: result.latitude,
    longitude: result.longitude,
    name: result.name,
    address: result.address
  }
  
  selectedLocation.value = location
  loadMapWithLocation(location)
  clearSearchResults()
}

// 清除搜索结果
const clearSearchResults = () => {
  searchResults.value = []
}

// 加载指定位置的地图
const loadMapWithLocation = async (location: LocationData) => {
  try {
    const params = new URLSearchParams({
      address: `${location.latitude},${location.longitude}`,
      zoom: mapZoom.value.toString()
    })
    const response = await anyGet(`/api/map/static-map?${params.toString()}`)
    
    if (response && response.data) {
      let imageUrl = null
      if (typeof response.data === 'string') {
        imageUrl = response.data
      } else if (response.data && typeof response.data === 'object') {
        imageUrl = response.data.url || response.data.imageUrl || response.data.mapUrl
      }
      
      if (imageUrl) {
        mapUrl.value = imageUrl
      } else {
        // 如果没有返回URL，使用默认占位图
        mapUrl.value = `https://via.placeholder.com/400x300/f0f0f0/999999?text=${encodeURIComponent(location.name || '地图位置')}`
      }
    } else {
      // 如果没有返回数据，使用默认占位图
      mapUrl.value = `https://via.placeholder.com/400x300/f0f0f0/999999?text=${encodeURIComponent(location.name || '地图位置')}`
    }
  } catch (error) {
    console.error('加载地图失败:', error)
    // 使用占位图显示错误信息
    mapUrl.value = `https://via.placeholder.com/400x300/ffebee/d32f2f?text=${encodeURIComponent('地图加载失败')}`
    message.error('地图加载失败')
  }
}

// 获取当前位置
const getCurrentLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      async (position) => {
        const location: LocationData = {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude
        }
        
        // 获取地址信息
        try {
          if (mapConfig.webApiKey) {
            // 优先使用前端直接调用高德API
            const result = await reverseGeocodeWithAmap(location.longitude, location.latitude)
            location.address = result.address
            location.name = result.name || '当前位置'
          } else {
            // 回退到后端接口
            const response = await anyPost('/api/map/reverse-geocode', {
              latitude: location.latitude,
              longitude: location.longitude
            })
            
            if (response && response.data) {
              location.address = response.data.address
              location.name = response.data.name || '当前位置'
            }
          }
        } catch (error) {
          console.error('获取地址信息失败:', error)
          location.name = '当前位置'
        }
        
        selectedLocation.value = location
        loadMapWithLocation(location)
        message.success('定位成功')
      },
      (error) => {
        console.error('定位失败:', error)
        message.error('定位失败，请检查浏览器定位权限')
      }
    )
  } else {
    message.error('浏览器不支持定位功能')
  }
}

// 地图点击事件（模拟）
const handleMapClick = async (event: MouseEvent) => {
  // 这里是简化的实现，实际应该根据点击位置计算经纬度
  // 由于使用的是静态地图，这里只是示例
  message.info('静态地图暂不支持点击选点，请使用搜索功能')
}

// 确认选择
const confirmSelection = () => {
  if (selectedLocation.value) {
    emit('update:modelValue', selectedLocation.value)
    emit('change', selectedLocation.value)
    message.success('位置选择成功')
  }
}

// 清除选择
const clearSelection = () => {
  selectedLocation.value = undefined
  mapUrl.value = ''
  emit('update:modelValue', undefined)
  emit('change', undefined)
}

// 获取标记点样式
const getMarkerStyle = () => {
  // 简化实现，将标记点放在地图中心
  return {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -100%)'
  }
}

// 地图加载事件
const onMapLoad = () => {
  // 地图加载成功
}

const onMapError = () => {
  message.error('地图加载失败')
}


</script>

<style scoped>
.map-location-picker {
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
}



.search-section {
  padding: 16px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.search-input {
  width: 100%;
}

.search-results {
  max-height: 200px;
  overflow-y: auto;
  border-bottom: 1px solid #e8e8e8;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: #f5f5f5;
  border-bottom: 1px solid #e8e8e8;
}

.results-title {
  font-weight: 500;
  color: #333;
}

.results-list {
  max-height: 160px;
  overflow-y: auto;
}

.result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.result-item:hover {
  background-color: #f5f5f5;
}

.result-item:last-child {
  border-bottom: none;
}

.result-info {
  flex: 1;
}

.result-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.result-address {
  font-size: 12px;
  color: #666;
}

.location-text {
  font-size: 12px;
  color: #999;
}

.map-display {
  border-bottom: 1px solid #e8e8e8;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.map-title {
  font-weight: 500;
  color: #333;
}

.map-actions {
  display: flex;
  gap: 8px;
}

.map-container {
  position: relative;
  height: 300px;
  background: #f5f5f5;
}

.map-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
}

.map-content {
  position: relative;
  width: 100%;
  height: 100%;
}

.map-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: crosshair;
}

.map-marker {
  position: absolute;
  z-index: 10;
  pointer-events: none;
}

.marker-icon {
  font-size: 24px;
  color: #ff4d4f;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
}

.selected-location {
  padding: 16px;
}

.location-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.location-title {
  font-weight: 500;
  color: #333;
}

.location-details {
  space-y: 8px;
}

.location-item {
  display: flex;
  margin-bottom: 8px;
}

.location-item:last-child {
  margin-bottom: 0;
}

.label {
  min-width: 80px;
  color: #666;
  font-size: 14px;
}

.value {
  flex: 1;
  color: #333;
  font-size: 14px;
  word-break: break-all;
}
</style>